package cn.nbs.cart.web.servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.hkr.servlet.BaseServlet;
import cn.nbs.book.entity.Book;
import cn.nbs.cart.entity.CartItem;
import cn.nbs.cart.service.CartItemService;
import cn.nbs.user.entity.User;

@WebServlet("/CartItemServlet")
public class CartItemServlet extends BaseServlet{
	private CartItemService service = new CartItemService();
	
	/**
	 * 添加购物车
	 * @param request
	 * @param response
	 * @return
	 */
	public String add(HttpServletRequest request,HttpServletResponse response){
		//判断当期用户是否登录，若没有登录，则跳转到登陆页面，否则正常添加
		User u = (User)request.getSession().getAttribute("user");
		if (u == null) {
			return "r:/jsps/user/login.jsp";
		}else{
			//就将bid  user  quantity 存到数据库里
			String bid = request.getParameter("bid");
			//CartItem(cid,quantity,Book,User)
			Book book = new Book();
			book.setBid(bid);
			
			int quantity = Integer.valueOf(request.getParameter("quantity"));
			
			CartItem item  = new CartItem();
			item.setBook(book);
			item.setQuantity(quantity);
			item.setUser(u);
			service.add(item);
			//查询用户的所有条目然后在显示
			
			return  myCart(request,response);
			
		}
	}
	
	/**
	 * 将当前用户的购物车信息展示出来
	 * @param request
	 * @param response
	 * @return
	 */
	public String myCart(HttpServletRequest request,HttpServletResponse response){
		//过滤没有登录的用户
		User u = (User)request.getSession().getAttribute("user");
		if (u == null) {
			return "r:/index.jsp";
		}else{
			//查询当前用户所有的购物车信息
			List<CartItem> list = service.findByUid(u.getUid());
		
			request.setAttribute("cartItemList", list);
			
			return "f:/jsps/cart/list.jsp";
		}
		
	}
	
	
	
		
}
